/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务                                                   
*│　作    者：sys                                              
*│　创建时间：2020-12-02 14:55:26   
*│　说    明：代码生成器生成   
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
	/// SysPermission服务层
	/// </summary>
    public class SysPermissionService: ISysPermissionService
    {
        private readonly ISysPermissionRepository _repository;
        private IMapper _mapper;

        public SysPermissionService(ISysPermissionRepository repository,IMapper mapper)
        {
            _mapper = mapper;
            _repository = repository;
        }

        public async Task<IApiResult> Add(MenuAddModel model)
        {
            var entity = _mapper.Map<SysPermissionEntity>(model);
            entity.Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
            entity.CreateTime = DateTime.Now;
            entity.Type = 0;
            entity.Platform = 0;
            var res= await _repository.InsertAsync(entity);
            if (res.IsNull())
                return ApiResult.NotOk("新增失败");
            return ApiResult.Ok();
        }

        public async Task<IApiResult> Delete(string id)
        {
            var list = await _repository.QueryChildren(id);
            var ids = list.Select(t => t.Id).Distinct().ToList();
            var count= await _repository.DeleteManyAsync(ids, "SysPermission");
            if (count <= 0)
                return ApiResult.NotOk("删除失败");
            return ApiResult.Ok();
        }

        public async Task<IApiResult> GetTree()
        {
            var list = await _repository.GetAllAsync();
            var treeList = new List<MenuTreeResModel>();
            foreach (var item in list.Where(m => m.ParentId.IsNull()&&m.Type==0).OrderBy(m => m.Sort))
            {
                //获得子级
                var children = RecursionOrganize(list.ToList(), new List<MenuTreeResModel>(), item.Id);
                treeList.Add(new MenuTreeResModel()
                {
                    Id = item.Id,
                    Title = item.Name,
                    Spread = children.Count > 0,
                    Children = children.Count == 0 ? null : children
                });
            }
            return ApiResult.Ok(treeList);
        }

        public async Task<IApiResult> Query(MenuQueryModel model)
        {
            return ApiResult.Ok(await _repository.Query(model));
        }

        public async Task<IApiResult> QueryById(string id)
        {
            var data = await _repository.GetAsync(id);
            var parent = await _repository.GetAsync(data.ParentId);
            data.ParentName = parent?.Name;
            return ApiResult.Ok(data);
        }

        public async Task<IApiResult> Sort(string p, string i, int o)
        {
            try
            {
                int a = 0, b = 0, c = 0;
                var res = await _repository.QueryChildren(p);
                res.RemoveAll(x => x.Id == p);
                var list= res.OrderBy(m => m.Sort).ToList();
              
                if (list.Count > 0)
                {
                    var index = 0;
                    foreach (var item in list)
                    {
                        index++;
                        if (index == 1)
                        {
                            if (item.Id == i) //判断是否是头如果上升则不做处理
                            {
                                if (o == 1) //下降一位
                                {
                                    a = Convert.ToInt32(item.Sort);
                                    b = Convert.ToInt32(list[index].Sort);
                                    c = a;
                                    a = b;
                                    b = c;
                                    item.Sort = a;
                                    await _repository.UpdateAsync(item);
                                    var nitem = list[index];
                                    nitem.Sort = b;
                                    await _repository.UpdateAsync(nitem);
                                    break;
                                }
                            }
                        }
                        else if (index == list.Count)
                        {
                            if (item.Id == i) //最后一条如果下降则不做处理
                            {
                                if (o == 0) //上升一位
                                {
                                    a = Convert.ToInt32(item.Sort);
                                    b = Convert.ToInt32(list[index - 2].Sort);
                                    c = a;
                                    a = b;
                                    b = c;
                                    item.Sort = a;
                                    await _repository.UpdateAsync(item);
                                    var nitem = list[index - 2];
                                    nitem.Sort = b;
                                    await _repository.UpdateAsync(nitem);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (item.Id == i) //判断是否是头如果上升则不做处理
                            {
                                if (o == 1) //下降一位
                                {
                                    a = Convert.ToInt32(item.Sort);
                                    b = Convert.ToInt32(list[index].Sort);
                                    c = a;
                                    a = b;
                                    b = c;
                                    item.Sort = a;
                                    await _repository.UpdateAsync(item);
                                    var nitem = list[index];
                                    nitem.Sort = b;
                                    await _repository.UpdateAsync(nitem);
                                    break;
                                }
                                else
                                {
                                    a = Convert.ToInt32(item.Sort);
                                    b = Convert.ToInt32(list[index - 2].Sort);
                                    c = a;
                                    a = b;
                                    b = c;
                                    item.Sort = a;
                                    await _repository.UpdateAsync(item);
                                    var nitem = list[index - 2];
                                    nitem.Sort = b;
                                    await _repository.UpdateAsync(nitem);
                                    break;
                                }
                            }
                        }
                    }
                }
                return ApiResult.Ok();
            }
            catch (Exception ex)
            {
                return ApiResult.NotOk(ex.Message);
            }
           
        }
    

        public async Task<IApiResult> Update(MenuUpdateModel model)
        {
            var entity = _mapper.Map<SysPermissionEntity>(model);
            var res= await _repository.UpdateAsync(entity);
            if (!res)
                return ApiResult.NotOk("更新失败");
            return ApiResult.Ok();
        }

        /// <summary>
        /// 递归部门
        /// </summary>
        /// <param name="sourceList">原数据</param>
        /// <param name="list">新集合</param>
        /// <param name="guid">父节点</param>
        /// <returns></returns>
        List<MenuTreeResModel> RecursionOrganize(List<SysPermissionEntity> sourceList, List<MenuTreeResModel> list, string id)
        {
            foreach (var row in sourceList.Where(m => m.ParentId == id&&m.Type==0).OrderBy(m => m.Sort))
            {
                var res = RecursionOrganize(sourceList, new List<MenuTreeResModel>(), row.Id);
                list.Add(new MenuTreeResModel()
                {
                    Id = row.Id,
                    Title = row.Name,
                    Spread = res.Count > 0,
                    Children = res.Count > 0 ? res : null
                });
            }
            return list;
        }
    }
}